package ar.com.fracervellera.server.services;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;

import javax.jdo.PersistenceManager;

import ar.com.fracervellera.model.Project;
import ar.com.fracervellera.server.repository.ProjectDAO;
import ar.com.fracervellera.server.repository.imp.ProjectDAOImp;
import ar.com.fracervellera.web.command.ProjectForm;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.appengine.repackaged.com.google.common.collect.SortedArraySet;

public class ProjectServiceImp implements ProjectService {
	private static ProjectServiceImp pss = null;
	private ProjectDAO projectDao = ProjectDAOImp.getInstance();
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	private ProjectServiceImp() {
		super();
	}
	
	public static ProjectServiceImp GetInstance() {
		if(pss == null) {
			pss = new ProjectServiceImp();
		}
		return pss;
	}
	
	public byte[] getFixedImage(BlobKey key ,int width, int height) {
		byte[] oldImageData = blobstoreService.fetchData(key, 0, BlobstoreService.MAX_BLOB_FETCH_SIZE - 1);
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
		Transform resize = ImagesServiceFactory.makeResize(width,height);
		Image newImage = imagesService.applyTransform(resize, oldImage);
		return newImage.getImageData();
	}
	
	public List<Project> getLastProjects(PersistenceManager pm) {
		List<Project> allProjects = projectDao.getAllProjects(pm);
		
		Comparator<Project> comparator = new Comparator<Project>() {

			@Override
			public int compare(Project arg0, Project arg1) {
				return (int) (arg1.getCreateDate() - arg0.getCreateDate());
			}
			
		};
		SortedSet<Project> sortedProject = new SortedArraySet<Project>(comparator,allProjects.size()); 
		sortedProject.addAll(allProjects);
		return new LinkedList<Project>(sortedProject);
	}

	@Override
	public List<Project> getAll(PersistenceManager pm) {
		return projectDao.getAllProjects(pm);
	}

	@Override
	public void create(ProjectForm form, PersistenceManager pm) {
		projectDao.create(form, pm);
	}

	@Override
	public void delete(Project project, PersistenceManager pm) {
		// TODO: Develop delete project implementation
		
	}

	@Override
	public void update(Project project, PersistenceManager pm) {
		// TODO Develop update project implementation.
		
	}


	
}
